package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.AES;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.annotate.Atomization;
import com.example.demo.common.Result;
import com.example.demo.entity.Record;
import com.example.demo.entity.Winbidder;
import com.example.demo.entity.dto.CompanyDTO;
import com.example.demo.entity.vo.CompanyVO;
import com.example.demo.mapper.RecordMapper;
import com.example.demo.service.TransactionService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tender")
@Api(tags = "1、招标管理")
@ApiSupport(author = "罗海林", order = 1)
@Validated
@RequiredArgsConstructor
@Slf4j
public class TenderController {

    private final RecordMapper recordMapper;
    private final TransactionService transactionService;

    @PostMapping("/test1")
    public String test1() {
        Record info = new Record() {{
            setContent("王彦远能否再聚");
            setType("add");
        }};

        /*UpdateWrapper<Record> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("recordid", "luohailinysyl");*/

        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("recordid", "luohailinysyl");

        int result = recordMapper.update(info, queryWrapper);

        Result res = new Result();
        res.ok();
        res.put("result", result);
        return res.toString();
    }

    @PostMapping("/test2")
    public String test2() {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("content");
        queryWrapper.eq("content", "罗海林去创业了");
        //queryWrapper.eq("id", "33");

        //Record info = recordMapper.selectOne(queryWrapper);
        Long count = recordMapper.selectCount(queryWrapper);

        Result res = new Result();
        res.ok();
        //res.put("info", info);
        res.put("count", count);
        return res.toString();
    }

    @PostMapping("/test3")
    public String test3() {
        Page<Record> page = new Page<>(2, 2);//参数：1-第X页，2-每页X条

        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "type", "module", "content");
        queryWrapper.like("content", "创业");

        Page<Record> page1 = recordMapper.selectPage(page, queryWrapper);
        System.out.println("page1 = " + page1);
        System.out.println("page1.getSize() = " + page1.getSize());
        System.out.println("page1.getCurrent() = " + page1.getCurrent());
        System.out.println("page1.getPages() = " + page1.getPages());
        System.out.println("page1.getTotal() = " + page1.getTotal());
        System.out.println("page1.getRecords() = " + page1.getRecords());
        System.out.println("page1.是否有上一页 :" + page1.hasPrevious());
        System.out.println("page1.是否有下一页 :" + page1.hasNext());

        return "true";
    }

    @PostMapping("/test4")
    public Result test4() {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("type", "module", "content");
        queryWrapper.eq("module", "中标企业列表页");
        queryWrapper.like("type", "dd");

        List<Map<String, Object>> list = recordMapper.selectMaps(queryWrapper);

        Result res = new Result();
        res.ok();
        res.put("list", list);
        return res;
    }

    @PostMapping("/test5")
    public String test5() {
        String content = "王彦远当年谢谢你";
        Record info = new Record() {{
            setRecordid("luohailinysyl");
            setContent(content);
            setType("update");
        }};
        int result = recordMapper.insert(info);

        Result res = new Result();
        res.ok();
        res.put("result", result);
        return res.toString();
    }

    @PostMapping("/test6")
    public String test6() {
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("recordid", "luohailinysyl");

        int result = recordMapper.delete(queryWrapper);

        Result res = new Result();
        res.ok();
        res.put("result", result);
        return res.toString();
    }

    @PostMapping("/test7")
    public Result test7() {
        String type = "update";

        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        /*queryWrapper.select("type", "content");
        queryWrapper.like(type.equals("update"), "content", "彦远");*/

        queryWrapper.lambda().select(Record::getType, Record::getContent, Record::getRemark);
        queryWrapper.lambda().like(type.equals("update"), Record::getContent, "修改");

        List<Record> list = recordMapper.selectList(queryWrapper);

        Result res = new Result();
        res.ok();
        res.put("list", list);
        return res;
    }

    @PostMapping("/test8")
    public String test8() {
        LambdaQueryWrapper<Record> query = new LambdaQueryWrapper<>();
        query.select(Record::getType, Record::getModule, Record::getContent);
        query.eq(Record::getModule, "中标企业列表页");
        query.like(Record::getType, "dd");
        query.clear();

        query.select(Record::getContent);
        query.eq(Record::getType, "update");


        List<Record> list = recordMapper.selectList(query);

        Result res = new Result();
        res.ok();
        res.put("list", list);
        return res.toString();
    }

    @PostMapping("/test9")
    public String test9() {
        MPJLambdaWrapper<Record> query = new MPJLambdaWrapper<>();
        query.select(Record::getRecordid, Record::getContent, Record::getAssociation, Record::getOperater, Record::getOperatetime);
        query.select(Winbidder::getCompany, Winbidder::getAddress, Winbidder::getPhone);
        query.leftJoin(Winbidder.class, Winbidder::getCompany, Record::getAssociation);
        query.isNotNull(Record::getAssociation);
        query.ne(Record::getAssociation, "");

        //List<CompanyVO> list = recordMapper.selectJoinList(CompanyVO.class, query);
        Page<CompanyVO> page = recordMapper.selectJoinPage(new Page(2, 1), CompanyVO.class, query);

        Result res = new Result();
        res.ok();
        res.put("list", page.getRecords());
        return res.toString();
    }

    @PostMapping("/test10")
    @ApiOperation(value = "test10", response = Result.class)
    @ApiOperationSupport(author = "罗海林", order = 24, includeParameters = { "address", "creater" })
    //@Transactional(rollbackFor = Exception.class)
    @Atomization
    public Result test10(@RequestBody @Validated({ CompanyDTO.Atomization.class }) CompanyDTO companyDTO) {
        Record info = new Record() {{
            setRecordid("luohailinysyl");
            setContent("彦远我想你");
            setType("update");
        }};

        int result = recordMapper.insert(info);
        log.info("第1次插入数据库完成");

        transactionService.sendQueue();

        /*String name = null;
        if (name.equals("远啊")) {
            name = "lhlysyl";
        }*/

        Record info2 = new Record() {{
            setRecordid("luohailinysyl2");
            setContent("彦远我想你2");
            setType("update");
        }};

        result = recordMapper.insert(info2);
        log.info("第2次插入数据库完成");

        Result res = new Result().ok();
        res.put("result", result);
        return res;
    }

    @Test
    public void test111() {
        String randomKey = AES.generateRandomKey();
        System.out.println("randomKey：" + randomKey);

        String data = "", result = "";

        data = "root";
        result = AES.encrypt(data, randomKey);
        System.out.println("username：" + result);

        data = "214luohailin";
        result = AES.encrypt(data, randomKey);
        System.out.println("password：" + result);

        data = "jdbc:mysql://localhost:3306/tender?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC";
        result = AES.encrypt(data, randomKey);
        System.out.println("url：" + result);
    }








    @PostMapping("/execTenderAuto")
    @ApiOperation(value = "启动自动化软件，获取招标信息")
    public String execTenderAuto() throws Exception {
        //检查软件是否已打开，若是则关闭软件
        Process process = Runtime.getRuntime().exec("tasklist");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains("Tax.exe")) {
                //关闭该应用程序
                ProcessBuilder pb = new ProcessBuilder("taskkill", "/F", "/IM", "Tax.exe");
                pb.start();

                Thread.sleep(1000);
                break;
            }
        }

        // 重新打开软件
        Runtime.getRuntime().exec("D:\\project\\csharp\\tender\\Tax\\bin\\Debug\\Tax.exe");

        // 模拟按键操作
        Robot robot = new Robot();
        // 等待2秒钟，确保软件已经打开
        robot.delay(2000);

        // 模拟按下Alt与菜单键
        robot.keyPress(KeyEvent.VK_ALT);
        robot.delay(500);
        robot.keyPress(KeyEvent.VK_Z);
        robot.delay(500);
        robot.keyPress(KeyEvent.VK_Y);
        robot.delay(500);

        // 模拟释放菜单键和Alt键
        robot.keyRelease(KeyEvent.VK_Y);
        robot.delay(500);
        robot.keyRelease(KeyEvent.VK_Z);
        robot.delay(500);
        robot.keyRelease(KeyEvent.VK_ALT);

        Result res = new Result();
        res.ok();
        return res.toString();
    }
}
